# -*- coding: utf-8 -*-
"""
@Time： 2023/12/20 16:20
@Auth： gubei
@File： main.py
@IDE：PyCharm
@Description：服务入口
"""
import platform
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
from fastapi.openapi.utils import get_openapi
from fastapi.staticfiles import StaticFiles

from core import server
from env import setting

app = server.InitializeApp()

# 获取基础 FastAPI 应用程序
if isinstance(app, FastAPI):
    # 添加自定义文档URL
    if not setting.APP_MODE:  # 仅在非生产模式下启用文档
        # 配置OpenAPI和文档URL
        app.openapi_url = "/api/openapi.json"
        app.docs_url = None  # 禁用默认文档路径
        app.redoc_url = None  # 禁用默认ReDoc路径
        
        # 挂载静态文件
        app.mount("/static", StaticFiles(directory="templates/static"), name="static")

        def custom_openapi():
            """
            自定义OpenAPI模式
            """
            if app.openapi_schema:
                return app.openapi_schema
            
            openapi_schema = get_openapi(
                title=setting.APP_TITLE,
                version="1.0.0",
                description="""
                {}
                
                ## 认证
                
                所有API（除了/api/token）都需要Bearer令牌认证。
                
                1. 获取令牌: 通过POST /api/token获取访问令牌
                2. 使用令牌: 在所有请求的Header中添加 `Authorization: Bearer {{token}}`
                
                ## 错误处理
                
                所有响应遵循统一格式:
                
                ```json
                {{
                    "code": 200,  // HTTP状态码
                    "msg": "SUCCESS",  // 响应消息
                    "data": {{}}  // 响应数据(可选)
                }}
                ```
                
                错误响应格式:
                
                ```json
                {{
                    "code": 400,  // HTTP状态码
                    "msg": "错误消息",  // 错误详情
                    "data": null  // 可能包含更多错误信息
                }}
                ```
                """.format(setting.APP_DESCRIPTION),
                routes=app.routes,
            )
            
            # 添加安全定义（指定所有API都使用Bearer令牌认证）
            openapi_schema["components"] = {
                "securitySchemes": {
                    "Bearer": {
                        "type": "http",
                        "scheme": "bearer",
                        "bearerFormat": "JWT"
                    }
                }
            }
            openapi_schema["security"] = [{"Bearer": []}]
            
            app.openapi_schema = openapi_schema
            return app.openapi_schema
        
        app.openapi = custom_openapi
        
        @app.get("/docs", include_in_schema=False)
        async def custom_swagger_ui_html():
            """自定义Swagger UI页面"""
            return get_swagger_ui_html(
                openapi_url=app.openapi_url,
                title=f"{app.title} - API文档",
                oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
                swagger_js_url="/static/swagger-ui-bundle.js",
                swagger_css_url="/static/swagger-ui.css",
                swagger_favicon_url="/static/favicon.png",
            )

        @app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
        async def swagger_ui_redirect():
            """Swagger UI OAuth2重定向"""
            return get_swagger_ui_oauth2_redirect_html()

        @app.get("/redoc", include_in_schema=False)
        async def redoc_html():
            """ReDoc文档页面"""
            return get_redoc_html(
                openapi_url=app.openapi_url,
                title=f"{app.title} - ReDoc",
                redoc_js_url="/static/redoc.standalone.js",
                redoc_favicon_url="/static/favicon.png",
                with_google_fonts=False,
            )
    
    # 添加CORS支持
    app.add_middleware(
        CORSMiddleware,
        allow_origins=setting.CORS_ORIGINS,
        allow_credentials=setting.CORS_ALLOW_CREDENTIALS,
        allow_methods=setting.CORS_ALLOW_METHODS,
        allow_headers=setting.CORS_ALLOW_HEADERS,
    )

